package wang.lxl.concurrent.lockTest;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        ReadWriteLockDemo lockDemo = new ReadWriteLockDemo();
        Random random = new Random();
        new Thread(()->lockDemo.set(random.nextInt()),"Write: ").start();
        for (int i = 1; i < 21; i++) {
            new Thread(()->lockDemo.get(),"Read : "+i).start();
        }
    }
}

/**
 * ReadWriteLock: 读写锁:读锁是共享的不互斥(一个线程获取到读锁别的线程也可以获取读锁).
 * 写锁是独占锁是互斥的(一个线程获取到锁,别的线程就无法获取锁).
 * 读/写,  写/写  是需要独占的
 * 读/读 共享锁,不互斥
 */
class ReadWriteLockDemo {
    private int number;
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    // 读取共享数据
    public void get(){
        lock.readLock().lock();// 读锁加锁
        try {
            System.out.println(Thread.currentThread().getName()+" : "+this.number);
        }finally {
            lock.readLock().unlock();// 读锁解锁
        }
    }

    // 写锁,独占锁
    public void set(int number) {
        lock.writeLock().lock();// 写锁加锁
        try {
            System.out.println(Thread.currentThread().getName());
            this.number = number;
        }finally {
            lock.writeLock().unlock();// 写锁,解锁
        }
    }
}